import { AppComponentBase } from '@shared/common/app-component-base';
import { LockAddressModalComponent } from './lock-address-modal/lock-address-modal.component';
import { ElectronicLockDTO, SiteDTO } from '@shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ServiceProxy } from '@shared/service-proxy/service-proxies';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { finalize } from 'rxjs/operators';
import { SetDeviceReasonModalComponent } from '../set-device-reason-modal/set-device-reason-modal.component';
import { FileUploader } from 'ng2-file-upload';
import { AppConsts } from '@shared/AppConsts';

@Component({
  selector: 'app-electronic-lock',
  templateUrl: './electronic-lock.component.html',
  styleUrls: ['./electronic-lock.component.less']
})
export class ElectronicLockComponent extends AppComponentBase implements OnInit {
  @ViewChild('lockAddressModal') lockAddressModal: LockAddressModalComponent;
  @ViewChild('setDeviceReasonModal') setDeviceReasonModal: SetDeviceReasonModalComponent;
  @ViewChild('fileSelect') uploadImg: any;
  tableHelper: NzTableHelper;
  uploader: FileUploader;
  loading = true;
  keyword: string;
  siteId: string;
  checkStatusList = [];
  statistics = { unAllot: "", inTransit: "", totalCount: "" };
  model: ElectronicLockDTO = new ElectronicLockDTO();
  isVisible = false;
  isOkLoading = false;
  isVisibleSite: boolean = false;
  validateForm: FormGroup;
  title: string;
  sites: SiteDTO[] = [];
  siteName: string;
  constructor(injector: Injector, private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    this.load();
    this.validateForm = this.fb.group({
      lockNo: [null, [Validators.required, Validators.maxLength(255)]],
      simNum: [null, [Validators.required, Validators.maxLength(255)]],
      siteId: [null, [Validators.nullValidator]],
    });
    this.siteId = "";

    this.checkStatusList = [
      { label: this.l('stock_in_transit'), value: 1, checked: true },
      { label: this.l('idle'), value: 2, checked: true }];
    this.getSites();
    this.initUploaders();
  }

  changeSite() {
    const site = this.sites.find(m => m.id == this.siteId);
    if (site) {
      this.siteName = site.siteName;
    }
    this.load();
  }

  getSites(): void {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
    this.getStatistics();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    const checkList = this.checkStatusList.filter(m => m.checked == true);
    const states = [];
    checkList.forEach(element => {
      states.push(element.value);
    });

    this._service.getPageElectronicLocksUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword, this.siteId, states).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;


    });
  }

  getStatistics() {
    this._service.findElectronicLockStatisticsUsingGET(this.siteId).subscribe(result => {
      this.statistics = result.result;
    })
  }

  reset() {
    this.tableHelper.pageIndex = 1;
    this.keyword = undefined;
    this.siteId = "";
    this.load();
  }

  setSite(id: string) {
    if (id) {
      this._service.getElectronicLockUsingGET(id).subscribe(result => {
        this.model = result.result;
      })
    }
    this.isVisibleSite = true;
  }
  showModal(id?: string): void {
    if (id) {
      this._service.getElectronicLockUsingGET(id).subscribe(result => {
        this.model = result.result;
        this.title = this.l('edit');
      })
    }
    else {
      this.model = new ElectronicLockDTO();
      this.validateForm.reset();
      this.model.siteId = "";
      this.title = this.l('create');
    }
    this.isVisible = true;
  }

  handleOk(): void {
    this.submitForm();
  }

  handleCancel(): void {
    this.isVisible = false;
    this.isVisibleSite = false;
  }

  submitForm(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) { // 验证通过
      if (this.model.id) {
        this._service.updateElectronicLockUsingPUT(this.model, this.model.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.handleCancel();
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        }
        )
      }
      else {
        this._service.createElectronicLockUsingPOST(this.model).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.handleCancel();
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        })
      }

    } else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  handleUsing(data: ElectronicLockDTO) {
    this.setDeviceReasonModal.show(data.id, data.enableFlag, "1");
  }

  showAddress(lockNo: string) {
    this.lockAddressModal.show(lockNo);
  }

  initUploaders(): void {
    this.uploader = new FileUploader({
      url: AppConsts.serverBaseUrl + '/api/siiat/v1/electroniclock/batchImport',
      method: 'POST',
      authToken: 'Bearer ' + abp.auth.getToken(),
      removeAfterUpload: true,
      autoUpload: true
    });
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };

    this.uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      if (ajaxResponse.success) {
        this.message.success(this.l('upload_success'));
      } else {
        this.message.error(this.l(ajaxResponse.error.message));
      }

      this.uploader.destroy();
      this.initUploaders();
      this.imgCropper();
      this.load();
    };
    this.uploader.onErrorItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      this.message.error(this.l(ajaxResponse.error.message));
      this.imgCropper();
    };
  }

  imgCropper() {
    // 一系列操作
    // 最后把input的value置空
    this.uploadImg.nativeElement.value = '';
  }
}
